package com.example.icongyou.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.icongyou.R;
import com.example.icongyou.activity.ChapterDetailActivity;
import com.example.icongyou.bean.Chapter;

import java.util.List;

public class ChapterAdapter extends RecyclerView.Adapter<ChapterAdapter.ChapterViewHolder> {

    private final Context mContext;
    private final List<Chapter> mChapterList;

    public ChapterAdapter(Context context, List<Chapter> chapterList) {
        this.mContext = context;
        this.mChapterList = chapterList;
    }

    @NonNull
    @Override
    public ChapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext)
                .inflate(R.layout.item_chapter_student, parent, false);
        return new ChapterViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ChapterViewHolder holder, int position) {
        Chapter chapter = mChapterList.get(position);
        if (chapter == null) return;

        // 章节序号（索引+1）
        holder.tvChapterNumber.setText(String.valueOf(position + 1));
        // 章节标题（使用Chapter类的getTitle()方法，与字段title匹配）
        holder.tvChapterTitle.setText(chapter.getTitle());

        // 点击跳转章节详情页
        holder.itemView.setOnClickListener(v -> {
            if (chapter.getChapterId() == null) {
                android.widget.Toast.makeText(mContext, "章节ID无效", android.widget.Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = new Intent(mContext, ChapterDetailActivity.class);
            intent.putExtra("chapterId", chapter.getChapterId()); // 传递章节ID
            intent.putExtra("chapterTitle", chapter.getTitle());  // 传递章节标题（使用getTitle()）
            mContext.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return mChapterList == null ? 0 : mChapterList.size();
    }

    static class ChapterViewHolder extends RecyclerView.ViewHolder {
        TextView tvChapterNumber;
        TextView tvChapterTitle;

        public ChapterViewHolder(@NonNull View itemView) {
            super(itemView);
            tvChapterNumber = itemView.findViewById(R.id.tv_chapter_index);
            tvChapterTitle = itemView.findViewById(R.id.tv_chapter_title);
        }
    }
}